"use client";
import React, {useState} from "react";
import {Button, Group, Modal, Radio, RadioGroup, Stack, TextInput} from "@mantine/core";
import {IconPlus} from "@tabler/icons-react";
import {useDisclosure} from "@mantine/hooks";
import {useForm} from "@mantine/form";
import {AddProjectProps} from "./interface";

const MODALS_RADIUS = "md";

function AddProject() {
  // [1] 易用性：按钮的loading状态（VPN访问时网络不佳，loading做到前端防抖，增强用户体验）
  const [loading, setLoading] = useState(false);

  // [2] 核心功能：表单收集
  const form = useForm<AddProjectProps>({
    mode: "uncontrolled",
    initialValues: {
      type: "个人项目",
      name: "",
    },
    validate: {
      // 小技巧: trim()可防止字符串前后存在空格
      type: (value) => (value.trim() === "工程项目" ? "禁止选择工程项目" : null),
      name: (value) => {
        if (!value.trim()) {
          return "名称不能为空"; // 空值提示
        }
        if (value.length > 30) {
          return "名称最多30个字符"; // 超过30个字符的提示
        }
        return null; // 验证通过
      },
    },
  });
  return (
    <form
      onSubmit={form.onSubmit((values) => {
        setLoading(true);
        // handleSubmit(values);
      })}
    >
      <Stack>
        <RadioGroup
          label="项目类型"
          key={form.key("type")} // 操作的锚点
          {...form.getInputProps("type")}
        >
          {/* 强制个人新建项目时只能选择个人项目 */}
          <Group>
            <Radio value="工程项目" label="工程项目" disabled />
            <Radio value="个人项目" label="个人项目" checked />
          </Group>
        </RadioGroup>
        <TextInput
          withAsterisk // 由于是新建表单，所以要有必填项标识
          label="项目名称"
          placeholder="请输入项目名称"
          radius={MODALS_RADIUS}
          key={form.key("name")} // 操作的锚点
          {...form.getInputProps("name")}
        />
        <Group justify="flex-end">
          <Button type="submit" loading={loading} radius={MODALS_RADIUS}>
            确定新增
          </Button>
        </Group>
      </Stack>
    </form>
  );
}

export function ButtonAdd() {
  const [opened, {open, close}] = useDisclosure(false);
  return (
    <>
      <Button size="xs" radius="sm" leftSection={<IconPlus size={12} />} onClick={open}>
        新增
      </Button>
      <Modal title="新建仿真项目（个人）" radius={MODALS_RADIUS} opened={opened} onClose={close}>
        <AddProject />
      </Modal>
    </>
  );
}
